import CommonModal from "@/components/CommonModal";
import Typography from "@/views/components/Typography";
import CommonLoading from "@/components/CommonLoading";
import CommonTable from "@/components/CommonTable";
import SubTitle from "@/views/components/SubTitle";
import ShopIcons from '@/views/components/ShopIcons';
import { useEffect, useState } from "react";
import { Alert, Button, Space, message } from "antd";
import { countOrderSum } from "../../config/CheckConfig";
import { getAfterSalesAddressList, syncAfterSalesAddress, agreeWithReturn } from "../../services";
import { find, findIndex } from "lodash";

/** 同意买家退货 */
function AgreeBuyerRefund(props) {
	const { item, selectKeys, tableList, handleOk, handleCancel } = props;
	const { scene } = item;
	const [isOk, setIsOk] = useState(false);
	const [loading, setLoading] = useState(false);

	const [open, setOpen] = useState(false);

	//配置信息
	const [storeConfig, setStoreConfig] = useState({});

	const columns = [
		{
			title: "联系人",
			dataIndex: "recieverName"
		},
		{
			title: "电话号码",
			dataIndex: "mobile",
			render: (t, r) => {
				return t || r.tel;
			}
		},
		{
			title: "详细地址",
			dataIndex: "address",
			render: (t, r) => {
				return `${r.receiverProvinc} ${r.receiverCity} ${r.receiverDistrict} ${r.receiverStreet} ${r.receiverDetail}`;
			}
		}
	];

	useEffect(() => {
		setOpen(true);
		initStoreData();
	}, []);

	//初始化信息
	const initStoreData = () => {
		const storeArr = [];
		const storeData = {};
		for (let i in selectKeys) {
			const obj = find(tableList, ["id", selectKeys[i]]);
			if (obj) {
				if (obj.ecStoreId && !storeArr.includes(obj.ecStoreId)) {
					storeArr.push(obj.ecStoreId);
					storeData[obj.ecStoreId] = {
						ecStoreId: obj.ecStoreId,
						ecStoreName: obj.ecStoreName,
						orderChannel: obj.orderChannel,
						addressList: []
					};
				}
			}
		}
		setLoading(true);
		const arr = [];
		for (let i in storeArr) {
			arr.push(getAfterSalesAddressList({ storeId: storeArr[i] }));
		}
		Promise.allSettled(arr).then(res => {
			for (let i in res) {
				const data = res[i].value.data;
				if (data.length > 0) {
					storeData[storeArr[i]].selectKeys = [data[0].id];
				} else {
					storeData[storeArr[i]].selectKeys = [];
				}
				storeData[storeArr[i]].addressList = data;
			}
			setStoreConfig(storeData);
		})
		setLoading(false);
	};

	//同步地址
	const handleSyncAddress = async storeId => {
		setLoading(true);
		const { success } = await syncAfterSalesAddress({ storeId });
		if (!success) {
			setLoading(false);
			return;
		}
		const res = await getAfterSalesAddressList({ storeId });
		setLoading(false);
		if (res.success) {
			if (res.data.length > 0) {
				storeConfig[storeId].addressList = res.data;

				//同步之后如果没有当前选择的地址数据，则重新勾选第一个
				const index = findIndex(res.data, ["id", storeConfig[storeId].addressList[0].id]);
				if (index == -1) {
					storeConfig[storeId].selectKeys = [res.data[0].id];
				}
				setStoreConfig(storeConfig);
			}

			message.info("同步成功！");
		}
	};

	const onOk = async () => {
		const arr = [];
		for (let i in storeConfig) {
			const item = storeConfig[i];
			if (item.selectKeys.length == 0) {
				message.info(`${item.ecStoreName}未选择退货地址`);
				return;
			}
			const senderAddressInfo = find(item.addressList, ["id", item.selectKeys[0]]);
			arr.push({
				ids: selectKeys,
				senderAddressInfo: {
					receiverAddressId: senderAddressInfo.addressId
				}
			});
		}
		setLoading(true);
		const { success } = await agreeWithReturn(arr);
		setLoading(false);
		if (success) {
			message.success("操作成功");
			setIsOk(true);
			setOpen(false);
		}
	};

	const onCancel = () => {
		setOpen(false);
	};

	const afterClose = () => {
		if (isOk) {
			handleOk();
		} else {
			handleCancel();
		}
	};

	//当前满足条件数量
	const countNum = countOrderSum(scene, selectKeys, tableList);

	return (
		<CommonModal title="同意买家退货" afterClose={afterClose} open={open} width="872px" onOk={onOk} onCancel={onCancel}>
			<Alert showIcon type="info" message="注：同意退货后，将会把操作和退货地址等信息同步给三方平台" />
			<div style={{ color: "#333", fontSize: "14px", margin: "16px 0" }}>
				<div>同意退款，只限操作以下一种状态的售后单：</div>
				<div style={{ marginTop: "12px" }}>
					已发货退货退款：<Typography type="error">{countNum}</Typography>
				</div>
				{Object.keys(storeConfig).map(v => {
					const item = storeConfig[v];
					const TableProps = {
						columns,
						data: item.addressList,
						rowKey: "id",
						rowSelection: {
							type: "radio",
							selectedRowKeys: item.selectKeys,
							onChange: selectKeys => {
								item.selectKeys = selectKeys;
								const obj = { ...storeConfig };
								obj[v] = item;
								setStoreConfig(obj);
							}
						}
					};
					return (
						<div key={v}>
							<Space style={{ marginTop: "12px" }}>
								<ShopIcons type={item.orderChannel} />
								{item.ecStoreName}
							</Space>
							<SubTitle
								wrapStyle={{ margin: "12px 0" }}
								symbol
								as="s2"
								title="选择退货地址"
								suffix={
									<Button onClick={() => handleSyncAddress(v)} type="link">
										同步三方平台退货地址
									</Button>
								}
							/>
							<CommonTable {...TableProps} />
						</div>
					);
				})}
			</div>
			<CommonLoading loading={loading} />
		</CommonModal>
	);
}

export default AgreeBuyerRefund;
